package com.luobd.db;

import java.sql.Connection;
import java.sql.DriverManager;

public class ConnectionManager {

    public static Connection getConnection(DatabaseConfig config) throws Exception {
        String url;
        String driverClass;
        switch (config.getDbType()) {
            case MYSQL:
                driverClass = "com.mysql.jdbc.Driver";
                url = String.format("jdbc:mysql://%s:%d/%s?characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true",
                        config.getHost(), config.getPort(), config.getDbName());
                break;
            case ORACLE:
                driverClass = "oracle.jdbc.OracleDriver";
                url = String.format("jdbc:oracle:thin:@%s:%d:%s",
                        config.getHost(), config.getPort(), config.getDbName());
                break;
            case HIVE:
                driverClass = "org.apache.hive.jdbc.HiveDriver";
                url = String.format("jdbc:hive2://%s:%d/%s",
                        config.getHost(), config.getPort(), config.getDbName());
                break;
            case DM:
                driverClass = "dm.jdbc.driver.DmDriver";
                url = String.format("jdbc:dm://%s:%d",
                        config.getHost(), config.getPort());
                break;
            default: throw new IllegalArgumentException("Unsupported database");
        }

        Class.forName(driverClass);
        return DriverManager.getConnection(url, config.getUsername(), config.getPassword());
    }

}
